package cn.rkylin.oms.system.flag.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.system.enterprise.domain.Enterprise;
import cn.rkylin.oms.system.enterprise.service.IEnterpriseService;
import cn.rkylin.oms.system.enterprise.vo.EnterpriseVO;
import cn.rkylin.oms.system.flag.domain.Flag;
import cn.rkylin.oms.system.flag.service.FlagServiceImpl;
import cn.rkylin.oms.system.flag.service.IFlagService;
import cn.rkylin.oms.system.flag.vo.FlagVO;

@Controller
@RequestMapping("/flag")
public class FlagController extends ApolloController {

    @Autowired
    private IEnterpriseService enterpriseService;
    
    @Autowired
    private IFlagService flagService;
    
    private static final String RESULT_SUCCESS_FLG = "success";  
    private static final String RESULT_ERROR_MESSAGE = "errormessage";
    private static final String RESULT_ROW_COUNT = "rowcount";
    
    /**
     * 旗帜表格数据
     * @param quickSearch
     * @param start
     * @param length
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/flagList", method = RequestMethod.GET)
    public Map<String, Object> getFlagList(String quickSearch,
                                           @RequestParam(required = false, defaultValue = "0") int start,
                                           @RequestParam(required = false, defaultValue = "10") int length,
                                           String formJson) throws Exception {
     // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 处理查询条件
            FlagVO param = new FlagVO();

            // 前台快速搜索条件
            if (quickSearch != null) {
                quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
                if (StringUtils.isNotEmpty(quickSearch)) {
                    param.setSearchCondition(quickSearch);
                }
            } else {
                // 高级查询检索条件
                formJson = URLDecoder.decode(formJson, "UTF-8");
                Map<String,String> mapflag = JSONObject.parseObject(formJson, Map.class);
                
                if (mapflag != null) {
                    if (StringUtils.isNotEmpty(mapflag.get("flag_type"))) {
                        param.setFlagType(mapflag.get("flag_type"));
                    }
                    if (StringUtils.isNotEmpty(mapflag.get("flag_name"))) {
                        param.setFlagName(mapflag.get("flag_name"));
                    }
                }
            }

            //当前用户的企业取得
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            List<String> list= new ArrayList<String>(currentUser.getEnterpriseMap().keySet());
            EnterpriseVO param1=new EnterpriseVO();
            if(list!=null && list.size()==0){
                return returnMap;
            }
            param1.setEnterpriseIdList(list);
            List lst = enterpriseService.getUserEnterpriseList(param1);
            if (lst!=null && lst.size()>0){
                List<String> listEntId = new ArrayList<String>();
                for (int i = 0 ; i < lst.size() ; i++){
                    Enterprise enterprise = (Enterprise)lst.get(i);
                    listEntId.add(enterprise.getEntId());
                }
                param.setListEntId(listEntId);
            }

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("flagTypeName", "flag_type");

            // 排序语句生成
            String orderStatement = getOrderString(FlagServiceImpl.class.getName(), "pageSelectFlag", replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            // 获取分页数据
            PageInfo<FlagVO> flagVOList = flagService.findByWhere(page, length, param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, flagVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, flagVOList.getTotal());
            returnMap.put(RETURN_DATA, flagVOList.getList());
        } catch (Exception ex) {
            ex.printStackTrace();
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }
    
    /**
     * 获取店铺明细信息
     *
     * @param shopId 店铺id
     * @return ShopVO的json串
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/flagDetail", method = RequestMethod.GET)
    public Map<String, Object> shopDetail(String flagId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
//            PageInfo<ShopVO> shopVOList = shopService.findByWhere(1, 1, param);
            FlagVO flagVO = flagService.getFlagById(flagId);
            if (flagVO != null) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, flagVO);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "该店铺不存在");
            }
        } catch (Exception ex) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }
    
    /**
     * 生成
     * @param shopId
     * @param shopName
     * @param splitType
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/createFlag")
    public Map<String, Object> createFlag(@RequestBody FlagVO fVo)
            throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();

        FlagVO flagVO = new FlagVO();
        flagVO.setFlagType(fVo.getFlagType());
        flagVO.setFlagName(fVo.getFlagName());
        flagVO.setEntId(fVo.getEntId());
        flagVO.setColor(fVo.getColor());
        flagVO.setUpdateTime(new Date());
        flagVO.setCreateTime(new Date());
        flagVO.setFlagId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
        flagVO.setRemark(fVo.getRemark());
        
        //分担规则生成
        Flag flag =  flagService.insert(flagVO);
        returnMap.put(RESULT_ROW_COUNT,1);
        returnMap.put(RESULT_SUCCESS_FLG,"Y");
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }
    
    /**
     * 修改
     * @param shopId
     * @param shopName
     * @param splitType
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/updateFlag")
    public Map<String, Object> updateFlag(@RequestBody FlagVO fVo)
            throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();

        FlagVO flagVO = flagService.getFlagById(fVo.getFlagId());
        flagVO.setFlagType(fVo.getFlagType());
        flagVO.setFlagName(fVo.getFlagName());
        flagVO.setEntId(fVo.getEntId());
        flagVO.setEntId(fVo.getEntId());
        flagVO.setColor(fVo.getColor());
        flagVO.setRemark(fVo.getRemark());
        flagVO.setUpdateTime(new Date());
        //分担规则生成
        Flag flag =  flagService.update(flagVO);
        returnMap.put(RESULT_ROW_COUNT,1);
        returnMap.put(RESULT_SUCCESS_FLG,"Y");
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }
    
    /**
     * 删除
     * @param shopId
     * @param shopName
     * @param splitType
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/deleteFlag")
    public Map<String, Object> deleteFlag(String flagID)
            throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        
        
//        returnMap = splitRuleService.getSplitRule(shopId, shopName, splitType);
//        if ("N".equals(returnMap.get(RESULT_SUCCESS_FLG))){
//            return returnMap;
//        }
//        FlagVO flagVO = new FlagVO();
//        flagVO.setFlagType(flagType);
//        flagVO.setFlagName(flagName);
//        flagVO.setEntId(entId);
//        flagVO.setEntId(entId);
//        flagVO.setColor(color);
        
        //分担规则生成
        int result =  flagService.delete(flagID);
        returnMap.put(RESULT_ROW_COUNT,result);
        returnMap.put(RESULT_SUCCESS_FLG,"Y");
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }
    
}
